package com.guldan.jaina.manager;

import java.util.ArrayList;
import java.util.List;

import com.guldan.core.exception.BusinessException;
import com.guldan.mapper.db.mapper.AreaMapperExt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.area.AreaDTO;
import com.guldan.jaina.dto.organization.OrganizationDTO;
import com.guldan.jaina.dto.organization.OrganizationSearchDTO;
import com.guldan.jaina.utils.AreaDomainConvertUtils;
import com.guldan.jaina.utils.OrganizationDomainConvertUtils;
import com.guldan.mapper.db.entity.Area;
import com.guldan.mapper.db.entity.Organization;
import com.guldan.mapper.db.entity.OrganizationExample;
import com.guldan.mapper.db.mapper.OrganizationMapperExt;

/**
 * Created by Silas.
 * Date: 2016/11/7
 * Time: 22:55
 */
@Service
public class OrganizationManager extends BaseManager {

    @Autowired
    private OrganizationMapperExt organizationMapperExt;

    @Autowired
    private AreaMapperExt areaMapperExt;

    //获取单个组织信息
    public OrganizationDTO get(Integer organizationId) {
        Organization organization = organizationMapperExt.selectByPrimaryKey(organizationId);
        if (organization != null) {
            OrganizationDTO dto = OrganizationDomainConvertUtils.convert(organization);
            if (organization.getOrgParentId() != null && organization.getOrgParentId() > 0) {
                Organization parentOrganization = organizationMapperExt.selectByPrimaryKey(organization.getOrgParentId());
                if (parentOrganization != null) {
                    dto.setOrgParentName(parentOrganization.getOrgName());
                    dto.setOrgParentCode(parentOrganization.getOrgCode());
                }
            }
            dto.setAreaName(areaMapperExt.selectByPrimaryKey(organization.getAreaId()).getAreaName());
            return dto;
        }
        return null;
    }

    //获取单个组织信息，通过org_code
    public OrganizationDTO getByOrgCode(String orgCode) {

        OrganizationDTO dto = new OrganizationDTO();
        OrganizationSearchDTO search = new OrganizationSearchDTO();
        search.setOrgCode(orgCode);
        List<Organization> entityList = organizationMapperExt.selectByExample(buildSearchExample(search));

        if (entityList != null && entityList.size() > 0) {
            Organization organization = entityList.get(0);

            dto = OrganizationDomainConvertUtils.convert(organization);
            if (organization.getOrgParentId() != null && organization.getOrgParentId() > 0) {
                Organization parentOrganization = organizationMapperExt.selectByPrimaryKey(organization.getOrgParentId());
                if (parentOrganization != null) {
                    dto.setOrgParentName(parentOrganization.getOrgName());
                    dto.setOrgParentCode(parentOrganization.getOrgCode());
                }
            }
            dto.setAreaName(areaMapperExt.selectByPrimaryKey(organization.getAreaId()).getAreaName());
        }
        return dto;
    }

    //判断某个机构是否已经存在
    private Boolean checkExist(String orgCode) {
        OrganizationExample example = new OrganizationExample();
        OrganizationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgCodeEqualTo(orgCode);
        criteria.andIsDeleteEqualTo(false);
        int count = organizationMapperExt.countByExample(example);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    //新增/更新单个组织，传入：OrganizationDTO
    public OrganizationDTO save(OrganizationDTO dto) throws BusinessException {


        Organization entity;
        if (dto.getOrgId() != null && dto.getOrgId() > 0) {

            entity = organizationMapperExt.selectByPrimaryKey(dto.getOrgId());
            entity.setAreaId(dto.getAreaId());
            entity.setBusinessDeptCode(dto.getBusinessDeptCode());
            entity.setOrgCode(dto.getOrgCode());
            entity.setOrgName(dto.getOrgName());
            entity.setOrgNameZw(dto.getOrgNameZw());
            entity.setOrgParentId(dto.getOrgParentId());
            entity.setOrgParentCode(dto.getOrgParentCode());
            entity.setOrgTypeCode(dto.getOrgTypeCode());
            entity.setRemark(dto.getRemark());

            entity.setDisabled(dto.getDisabled());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            organizationMapperExt.updateByPrimaryKeySelective(entity);
        } else {
            //判断是否存存在
            if (checkExist(dto.getOrgCode())) {
                throw new BusinessException("机构Code已存在");
            }
            entity = new Organization();
            entity.setAreaId(dto.getAreaId());
            entity.setBusinessDeptCode(dto.getBusinessDeptCode());
            entity.setOrgCode(dto.getOrgCode());
            entity.setOrgName(dto.getOrgName());
            entity.setOrgNameZw(dto.getOrgNameZw());
            entity.setOrgParentId(dto.getOrgParentId());
            entity.setOrgParentCode(dto.getOrgParentCode());
            entity.setOrgTypeCode(dto.getOrgTypeCode());
            entity.setRemark(dto.getRemark());

            entity.setDisabled(dto.getDisabled());
            entity.setCreator(dto.getModifier());
            entity.setCreateTime(DateUtil.getCurrentTime());
            organizationMapperExt.insertSelective(entity);
        }
        dto = OrganizationDomainConvertUtils.convert(entity);
        return dto;
    }

    //删除单个组织信息
    public Boolean delete(Integer organizationId) {
        Organization entity = organizationMapperExt.selectByPrimaryKey(organizationId);
        entity.setIsDelete(true);
        return organizationMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

    //分页查询组织信息列表
    public Pagination<OrganizationDTO> list(OrganizationSearchDTO organizationSearchDTO) {
        Pagination<OrganizationDTO> result = new Pagination<OrganizationDTO>(organizationSearchDTO.getCurrentPage(), organizationSearchDTO.getPerPage());
        OrganizationExample example = buildSearchExample(organizationSearchDTO);
        int total = organizationMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<OrganizationDTO> data = new ArrayList<OrganizationDTO>();
            List<Organization> list = organizationMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (Organization entity : list) {
                OrganizationDTO dto = OrganizationDomainConvertUtils.convert(entity);

                if (dto.getOrgParentId() != null && dto.getOrgParentId() > 0) {
                    Organization parentOrganization = organizationMapperExt.selectByPrimaryKey(dto.getOrgParentId());
                    if (parentOrganization != null) {
                        dto.setOrgParentName(parentOrganization.getOrgName());
                        dto.setOrgParentCode(parentOrganization.getOrgCode());
                    }
                }
                dto.setAreaName(areaMapperExt.selectByPrimaryKey(dto.getAreaId()).getAreaName());
                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    //build查询Example
    private OrganizationExample buildSearchExample(OrganizationSearchDTO search) {
        OrganizationExample example = new OrganizationExample();
        OrganizationExample.Criteria criteria = example.createCriteria();

        if (search.getOrgId() != null && search.getOrgId() > 0) {
            criteria.andOrgIdEqualTo(search.getOrgId());
        }
        if (search.getOrgParentId() != null && search.getOrgParentId() >= 0) {
            criteria.andOrgParentIdEqualTo(search.getOrgParentId());
        }
        if (search.getAreaId() != null && search.getAreaId() > 0) {
            criteria.andAreaIdEqualTo(search.getAreaId());
        }
        if (StringUtils.isNotBlank(search.getOrgTypeCode())) {
            criteria.andOrgTypeCodeEqualTo(search.getOrgTypeCode());
        }
        if (StringUtils.isNotBlank(search.getOrgCode())) {
            criteria.andOrgCodeEqualTo(search.getOrgCode());
        }
        if (StringUtils.isNotBlank(search.getOrgName())) {
            criteria.andOrgNameEqualTo(search.getOrgName());
        }

        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("org_id asc");
        }
        return example;
    }

    /**
     * 批量插入区域
     *
     * @param list
     * @return
     */
    public Boolean batchImport(List<OrganizationDTO> list) {
        if (list != null && list.size() > 0) {
            for (OrganizationDTO dto : list) {
                save(dto);
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
